package pl.edu.agh.mobsys.activities.soapactivities;

import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Packet;

import pl.edu.agh.mobsys.R;
import pl.edu.agh.mobsys.XmppApplication;
import pl.edu.agh.mobsys.data.SoapXmppMessage;
import pl.edu.agh.mobsys.soap.JobData;
import pl.edu.agh.mobsys.soap.SOAPBuilder;
import pl.edu.agh.mobsys.utils.Constants;
import pl.edu.agh.mobsys.utils.SmoaParser;
import pl.edu.agh.mobsys.utils.Constants.SmoaAgentType;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddJob extends Activity implements View.OnClickListener,
		DialogInterface.OnClickListener, OnKeyListener {

	private static final String TAG = "AddJob";
	private static int jobCount = 1;

	private EditText jobName;
	private EditText jobCommand;
	private EditText jobArguments;
	private Button addButton;
	private Button backButton;

	private XmppApplication app;
	private String alias;
	private org.jivesoftware.smack.Chat chat;
	private String notifierAgentName;
	private String jobReceiverAgentName;

	private PacketListener packetListener;

	private JobData jobToAdd;

	/*
	 * String[] info = {"what", "where", "why"}; String currentMenu;
	 */

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_job);

		jobName = (EditText) findViewById(R.id.jobName);
		jobCommand = (EditText) findViewById(R.id.jobCommand);
		jobArguments = (EditText) findViewById(R.id.jobArguments);
		addButton = (Button) findViewById(R.id.addButton);
		backButton = (Button) findViewById(R.id.backButton);

		addButton.setOnClickListener(this);
		backButton.setOnClickListener(this);

		app = (XmppApplication) getApplication();
		alias = getIntent().getStringExtra(Constants.ACTIVATED_CONTACT);

		notifierAgentName = getIntent().getStringExtra(
				SmoaAgentType.NOTIFIER.toString());
		jobReceiverAgentName = getIntent().getStringExtra(
				SmoaAgentType.JOB_RECEIVER.toString());

		packetListener = new PacketListener() {
			public void processPacket(final Packet packet) {
				processSmoaPacket(packet);
			}
		};
	}

	@Override
	protected void onResume() {
		super.onResume();
		chat = ((XmppApplication) getApplication()).getChat(alias,
				SmoaAgentType.JOB_RECEIVER);
		if (chat != null) {
			app.getXMPPConnection().addPacketListener(packetListener,
					SmoaParser.getSmoaPacketFilter());
		} else {
			Toast.makeText(getApplicationContext(),
					"Failed to create chat for alias: " + alias,
					Toast.LENGTH_SHORT).show();
		}
		jobName.setText("Job " + jobCount++);
	}

	@Override
	protected void onPause() {
		super.onPause();
		app.getXMPPConnection().removePacketListener(packetListener);
	}

	/*
	 * public boolean onCreateOptionsMenu(Menu menu) {
	 * super.onCreateOptionsMenu(menu); MenuItem item; item =
	 * menu.add("delete"); item.setIcon(R.drawable.bunny); item =
	 * menu.add("info"); item.setIcon(R.drawable.info); item = menu.add("star");
	 * item.setIcon(R.drawable.star); return true; }
	 * 
	 * public boolean onOptionsItemSelected(MenuItem item) {
	 * super.onOptionsItemSelected(item); if(item.hasSubMenu()==false) {
	 * if(item.getTitle() == "info") { currentMenu = "info";
	 * this.displayPopup("info items", this.info); } if(item.getTitle() ==
	 * "delete") { int index = listItems.getSelectedItemPosition();
	 * this.deleteItem(index); } } return true; }
	 */

	private void displayPopup(String title, String[] items) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(title);
		builder.setItems(items, this);
		builder.show();
	}

	public void onClick(View v) {
		if (v == this.addButton) {
			addButton.setClickable(false);
			backButton.setClickable(false);
			addJob();
		} else if (v == this.backButton) {
			Log.d(TAG, "Back");
			finish();
		}
	}

	private void addJob() {
		jobToAdd = new JobData(jobName.getText().toString(), jobCommand
				.getText().toString(), jobArguments.getText().toString());
		String SOAPAddJobMessage = SOAPBuilder.getRunMessage(jobToAdd);
		try {
			chat.sendMessage(new SoapXmppMessage(SOAPAddJobMessage));
		} catch (XMPPException e) {
			Toast.makeText(getApplicationContext(),
					R.string.chat_failed_to_send + " : " + e.getMessage(),
					Toast.LENGTH_SHORT).show();
			e.printStackTrace();
			finish();
		}
	}

	public boolean onKey(View v, int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
			// this.addItem(this.jobName.getText().toString());
		}
		return false;
	}

	public void onClick(DialogInterface dialog, int item) {

	}

	private void processSmoaPacket(final Packet packet) {
		final SmoaParser.ParsedMessage parsedMessage = SmoaParser
				.parseMessage(packet, notifierAgentName, jobReceiverAgentName);

		runOnUiThread(new Runnable() {
			public void run() {
				Log.d(TAG, parsedMessage.messageType + " message from notifier: "
						+ packet.toXML());
			}
		});

		if (parsedMessage.messageType == SmoaParser.MessageType.AddJobConfirmation) {
			jobToAdd.setAid(parsedMessage.id);

			runOnUiThread(new Runnable() {
				public void run() {
					Log.d(TAG, "Job id: " + parsedMessage.id + " state: "
							+ parsedMessage.info);
				}
			});

			app.getJobs(alias).put(jobToAdd.getAid(), jobToAdd);
			finish();
		} else if (parsedMessage.messageType == SmoaParser.MessageType.Fault) {
			finish();
		}
	}
}